package com.example.liuweather.android;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.liuweather.android.Fragment.ChooseAreaFragment;
import com.example.liuweather.android.db.County;
import com.example.liuweather.android.gson.Forecast;
import com.example.liuweather.android.gson.Weather;
import com.example.liuweather.android.service.AutoUpdateService;
import com.example.liuweather.android.util.HttpUtil;
import com.example.liuweather.android.util.LogUtil;
import com.example.liuweather.android.util.Utility;
import com.google.gson.Gson;
import com.qweather.sdk.bean.IndicesBean;
import com.qweather.sdk.bean.air.AirNowBean;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.IndicesType;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.weather.WeatherDailyBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.internal.Util;

public class WeatherActivity extends  BaseActivity {


    private ScrollView weatherLayout;
    private TextView titleCity;
    private TextView titleUpdateTime;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forecastLayout;
    private TextView aqiText;
    private TextView pm25Text;
    private TextView qltyText;
    private LinearLayout moreLayout;
    private TextView comfortText;
    private TextView carWashText;
    private TextView sportText;
    public ImageView bingPicImg;
    private Button navButton;
    private ListView lv;
    private ChooseAreaFragment chooseAreaFragment;


    // public 碎片中需要用到的控件及数据
    public SwipeRefreshLayout swipeRefresh;
    public DrawerLayout drawerLayout;
    public String weatherId; // 查询天气的地区id
    public String countyName; //查询天气的地区名

    public SharedPreferences prefs;
    private IntentFilter intentFilter;
    private MyBroadcastReceiver myBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_weather);
        // 初始化各控件
        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        qltyText = findViewById(R.id.qlty_text);
        moreLayout = findViewById(R.id.forecast_more);
        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
        lv = findViewById(R.id.search_result_list);
        // 获取碎片实例
        chooseAreaFragment = (ChooseAreaFragment) getSupportFragmentManager().findFragmentById(R.id.choose_area_fragment);


        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        // 设置下拉刷新进度条的颜色
        swipeRefresh.setColorSchemeResources(R.color.purple_500);
        // 滑动菜单控件
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        // 关闭抽屉侧滑，防止与碎片里面 HorizontalScrollView控件 失效
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        // 侧边菜单按钮
        navButton = (Button) findViewById(R.id.nav_button);
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清空搜索框数据
                // 调用碎片中的方法
                chooseAreaFragment.clearSearchEditText();
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("刷新", "onRefresh: ");
                requestWeatherForQWeather(weatherId);
            }
        });

        // Glide加载背景图片
        loadBingPic();

        // 获取weather_id 和 county_name
        Intent intent = getIntent();
        SharedPreferences prefs = PreferenceManager.
                getDefaultSharedPreferences(WeatherActivity.this);
        weatherId = intent.getStringExtra("weather_id");
        if("1".equals(weatherId)){
            // 已经请求过天气数据了，并从主活动过来的
            LogUtil.w("有缓存");
            weatherId = prefs.getString("weather_id",null);
            countyName = prefs.getString("county_name",null);
        }else {
            LogUtil.w("无缓存或从其他页面跳转进来");
            countyName = intent.getStringExtra("county_name");
        }

        // 请求数据，并更新视图
        weatherLayout.setVisibility(View.INVISIBLE);
        requestWeatherForQWeather(weatherId);

        // 激活服务
        Intent intentSer = new Intent(this, AutoUpdateService.class);
        startService(intentSer);
    }
    /**
     * 监听返回键
     * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){ // 按下返回键
            boolean isOpen = drawerLayout.isDrawerOpen(GravityCompat.START);
            LogUtil.w("抽屉是打开状态，正在关闭");
            if(isOpen) {
                // 关闭抽屉
                drawerLayout.closeDrawer(GravityCompat.START);
            }else return super.onKeyDown(keyCode, event);
        }
        return true;
    }

    /**
     * 加载必应每日一图
     */

    private void loadBingPic() {
        LogUtil.w("loadBingPic");
        // 这个直接获取图片信息
        String requestBingPic = "https://api.isoyu.com/bing_images.php";
        Glide.with(WeatherActivity.this).load(requestBingPic).into(bingPicImg);
    }

    /**
     * 根据天气id请求城市天气信息
     */
/*    public void requestWeather(String weatherId) { // 地区id
        String weatherUrl = "http://guolin.tech/api/weather?cityid=" +
                weatherId + "&key=98f7a7016c114044b830a0c7fbcec9a6";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 获取数据
                final String responseText =  response.body().string();
                // Log.d("test", "onResponse: " + responseText);
                // 解析数据
                final Weather weather = Utility.handleWeatherResponse(responseText);
                // 将当前线程切换到主线程
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(weather != null && "ok".equals(weather.getStatus())){
                            // 数据获取成功
                            // 获取SharedPreferences.Editor 对象
                            SharedPreferences.Editor editor = PreferenceManager
                                    .getDefaultSharedPreferences(WeatherActivity.this).edit();
                            // 添加数据
                            editor.putString("weather",responseText);
                            // 缓存
                            editor.apply();
                            showWeatherInfo(weather);
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT)
                                            .show();
                                }
                            });
                        }
                        // 刷新事件结束，并隐藏刷新进度条。
                        swipeRefresh.setRefreshing(false);
                    }
                });

            }
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT)
                        .show();
                // 刷新事件结束，并隐藏刷新进度条。
                swipeRefresh.setRefreshing(false);
            }

        });
        // 请求天气刷新背景图片
        loadBingPic();
    }*/
    /**
     * 根据城市地区id调用和风天气api接口，并处理展示数据
     */
    public void requestWeatherForQWeather(String locationID) {
        // 请求当天天气的基本信息
        QWeather.getWeatherNow(getApplicationContext(), locationID, new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable throwable) {
                LogUtil.w("WeatherActivity getWeather onError: " + throwable);
            }

            @Override
            public void onSuccess(WeatherNowBean weatherNowBean) {
                // 将类对象转为Json字符串
                LogUtil.w("WeatherActivity getWeather onSuccess: " + new Gson().toJson(weatherNowBean));
                // 请求状态成功
                if (Code.OK == weatherNowBean.getCode()) {
                    WeatherNowBean.NowBaseBean now= weatherNowBean.getNow();
                    // 缓存当前所在地区的id和名字
                    SharedPreferences.Editor editor = PreferenceManager.
                            getDefaultSharedPreferences(WeatherActivity.this).edit();
                    editor.putString("weather_id", locationID);
                    editor.putString("county_name", countyName);
                    editor.apply();

                    // 展示数据
                    showBasicInfo(now);
                    // 请求获取7天天气预报信息数据，并处理展示数据
                    request7DailyForQWeather(locationID);
                }else {
                    //查看请求错误状态码
                    Code code = weatherNowBean.getCode();
                    LogUtil.w("WeatherActivity failed code: " + code);
                }
            }
        });
    }

    /*
     * 根据天气id获取城市未来7天的天气预报
     */
    public void request7DailyForQWeather(String locationID) {
        // 查询天气预报
        QWeather.getWeather7D(getApplicationContext(), locationID, new QWeather.OnResultWeatherDailyListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w("WeatherActivity getWeatherDaily onError: " + e);
            }

            @Override
            public void onSuccess(WeatherDailyBean weatherDailyBean) {
                LogUtil.w("WeatherActivity getWeatherDaily onSuccess: " + new Gson().toJson(weatherDailyBean));
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherDailyBean.getCode()) {
                    List<WeatherDailyBean.DailyBean> dailyBeanList = weatherDailyBean.getDaily();
                    // 展示未来7天预报数据
                    show7DailyInfo(dailyBeanList);
                    // 请求城市当天的空气质量信息，并处理展示数据
                    requestAirForQWeather(locationID);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 绑定点击事件
                            moreLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(WeatherActivity.this, MoreActivity.class);
                                    // getFxLink 所查询城市的天气预报网页
                                    intent.putExtra("more_url", weatherDailyBean.getBasic().getFxLink());
                                    startActivity(intent);
                                }
                            });
                        }
                    });
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherDailyBean.getCode();
                    LogUtil.w("WeatherActivity failed code: " + code);
                }
            }
        });
    }
    /*
     * 根据天气id请求城市空气质量信息
     */
    public void requestAirForQWeather(String locationID) {
        // 查询当前空气质量
        QWeather.getAirNow(getApplicationContext(), locationID, Lang.ZH_HANS, new QWeather.OnResultAirNowListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w("WeatherActivity getAir onError: " + e);
            }

            @Override
            public void onSuccess(AirNowBean airNowBean) {
                if (Code.OK == airNowBean.getCode()) {
                    AirNowBean.NowBean now = airNowBean.getNow();
                    // 展示空气质量布局
                    showAirInfo(now);
                    // 请求城市当天的生活指数信息，并处理展示数据
                    requestIndicesForQWeather(locationID);
                } else {
                    //在此查看返回数据失败的原因
                    Code code = airNowBean.getCode();
                    LogUtil.w("WeatherActivity failed code: " + code);
                }
            }
        });
    } /*
     * 根据天气id请求城市生活指数信息
     */
    public void requestIndicesForQWeather(String locationID) {
        List<IndicesType> indicesTypes = new ArrayList<>();
        indicesTypes.add(IndicesType.COMF);
        indicesTypes.add(IndicesType.CW);
        indicesTypes.add(IndicesType.SPT);
        // 查询生活指数
        QWeather.getIndices1D(getApplicationContext(), locationID, Lang.ZH_HANS, indicesTypes, new QWeather.OnResultIndicesListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w("WeatherActivity getIndices3D onError: " + e);
            }

            @Override
            public void onSuccess(IndicesBean indicesBean) {
                if (Code.OK == indicesBean.getCode()) {
                    List<IndicesBean.DailyBean> dailyBeanList = indicesBean.getDailyList();
                    // 展示当天的生活指数及建议
                    showIndicesInfo(dailyBeanList);
                } else {
                    //在此查看返回数据失败的原因
                    Code code = indicesBean.getCode();
                    LogUtil.w("WeatherActivity failed code: " + code);
                }
            }
        });
    }
    /**
     * 处理并展示Weather实体类中的数据
     */
/*    private void showWeatherInfo(Weather weather) {
        String cityName = weather.getBasic().getCityName();
        String updateTime = weather.getBasic().getUpdate().getUpdateTime();
        String temperature = weather.getNow().getTemperature() + "℃";
        String weatherInfo = weather.getNow().getMore().getInfo();

        // 设置标题布局数据
        titleCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(temperature);
        weatherInfoText.setText(weatherInfo);
        // 此方法从ViewGroup中删除所有的子视图
        forecastLayout.removeAllViews();
        // 动态加载未来天气的子项布局
        for(Forecast f : weather.getForecastList()){
            // 加载每一项子项布局 注意这里返回的view是子布局 还没有添加到根布局
            View viewItem = LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false);
            // 获取子布局的控件
            TextView dateText = viewItem.findViewById(R.id.date_text);
            TextView infoText = viewItem.findViewById(R.id.info_text);
            TextView maxText = viewItem.findViewById(R.id.max_text);
            TextView minText = viewItem.findViewById(R.id.min_text);
            // 设置数据
            dateText.setText(f.getDate());
            infoText.setText(f.getMore().getInfo());
            maxText.setText(f.getTemperature().getMax());
            minText.setText(f.getTemperature().getMin());
            // 加入到根布局中
            forecastLayout.addView(viewItem);
        }

        // 设置AQI数据
        aqiText.setText(weather.getAqi().getCity().getAqi());
        pm25Text.setText(weather.getAqi().getCity().getPm25());
        comfortText.setText("舒适度：" + weather.getSuggestion().getComfort().getInfo());
        carWashText.setText("洗车建议：" + weather.getSuggestion().getCarWash().getInfo());
        sportText.setText("运动建议：" + weather.getSuggestion().getSport().getInfo());

        // 显示视图
        weatherLayout.setVisibility(View.VISIBLE);
    }*/
    /**
     * 展示当天天气基本信息
     */
    private void showBasicInfo(WeatherNowBean.NowBaseBean now) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String cityName = countyName;
                String time = now.getObsTime().substring(0, 10) + " " + now.getObsTime().substring(11, 16);
                String updateTime = "更新时间：" + time;
                String degree = now.getTemp();
                String weatherInfo = now.getText();

                titleCity.setText(cityName);
                titleUpdateTime.setText(updateTime);
                degreeText.setText(degree);
                weatherInfoText.setText(weatherInfo);
            }
        });
    }
    /**
     * 展示未来几天的天气信息
     */
    private void show7DailyInfo(List<WeatherDailyBean.DailyBean> dailyBeanList) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 此方法从ViewGroup中删除所有的子视图
                forecastLayout.removeAllViews();
                for (WeatherDailyBean.DailyBean dailyBean : dailyBeanList) {
                    // 加载每一项子项布局 注意这里返回的view是子布局 还没有添加到根布局
                    View view = LayoutInflater.from(WeatherActivity.this).inflate(R.layout.forecast_item, forecastLayout, false);
                    TextView dateText = view.findViewById(R.id.date_text);
                    TextView maxText = view.findViewById(R.id.max_text);
                    TextView minText = view.findViewById(R.id.min_text);
                    TextView infoText = view.findViewById(R.id.info_text);

                    dateText.setText(dailyBean.getFxDate());
                    maxText.setText(dailyBean.getTempMax() + "℃");
                    minText.setText(dailyBean.getTempMin() + "℃");
                    infoText.setText(dailyBean.getTextDay());
                    // 向根布局添加子布局
                    forecastLayout.addView(view);
                }
            }
        });
    }
    /**
     * 展示当天的aqi、pm25、空气质量
     */
    private void showAirInfo(AirNowBean.NowBean now) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                qltyText.setText(now.getCategory());
                aqiText.setText(now.getAqi());
                pm25Text.setText(now.getPm2p5());

            }
        });
    }
    /**
     * 展示当天的生活指数：舒适度、洗车、运动。及建议
     */
    private void showIndicesInfo(List<IndicesBean.DailyBean> dailyBeanList) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LogUtil.w("showIndicesInfo" + dailyBeanList.toString());
                String comfort = dailyBeanList.get(0).getName() + "：" + dailyBeanList.get(0).getCategory() + "。" + dailyBeanList.get(0).getText();
                String carWash = dailyBeanList.get(1).getName() + "：" + dailyBeanList.get(1).getCategory() + "。" + dailyBeanList.get(1).getText();
                String sport = dailyBeanList.get(2).getName() + "：" + dailyBeanList.get(2).getCategory() + "。" + dailyBeanList.get(2).getText();

                comfortText.setText(comfort);
                carWashText.setText(carWash);
                sportText.setText(sport);

               /* 显示页面之前必须先将请求获取数据这个异步操作完成
               即确保最后一个请求接口的回调函数中调用该函数，保证最后天气布局显示
                */
                // 天气布局显示
                weatherLayout.setVisibility(View.VISIBLE);
                // 关闭刷新事件，隐藏刷新进度条。
                swipeRefresh.setRefreshing(false);

            }
        });
    }
    // 自定义广播
    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 可以直接调用活动里面的方法
            // 获取SharedPreferences对象
            prefs = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
            // 获取当前最新缓存数据
            String weatherId = prefs.getString("weather_id",null);
            // 刷新每日一图
            loadBingPic();
            // 重新访问服务器，刷新页面
            // showWeatherInfo(weather);
            requestWeatherForQWeather(weatherId);
            LogUtil.w("onReceive: 收到服务广播，页面成功刷新一次");
        }
    }

    @Override
    protected void onStart() {
        // 重写onStart方法 注册广播
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.liuweather.android.service");
        myBroadcastReceiver = new MyBroadcastReceiver();
        registerReceiver(myBroadcastReceiver, intentFilter);
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        // 取消注册
        unregisterReceiver(myBroadcastReceiver);
        super.onDestroy();
    }
}